package com.cloud.sonixcamerademo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.deviceplug.*;
import com.jni.NativeMethods;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.usb.UsbDevice;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.Provider;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity  implements IUsbDevicePlugDelegate, AdapterView.OnItemClickListener {

    private static final int USB_DEVICE_INSERT = 0;
    private static final int USB_DEVICE_PERRMISSION = 1;
    private static final int USB_DEVICE_DETACHED = 2;
    private static final int USB_DEVICE_OPEN = 3;

    private Button readAiscRegisterBtn;
    private Button writeAiscRegisterBtn;
    private Button startBurnFirewareBtn;
    private EditText asicRegisterAddrTextEdit;
    private EditText asicRegisterDataTextEdit;
    private ListView fwFileNameListView;
    private ProgressBar curProgress;
    private boolean isBusy = false;
    private ArrayList<String> fwFileNames;
    private ArrayList<String> fwFilePaths;
    private int selFileNameIndex;

    private TextView devNameTextView;
    private TextView fwVersionTextView;

    private CameraControlTransfer cct;

    private Handler mHander = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case USB_DEVICE_INSERT:
                    UpdateCameraInfo();
                    break;
                case USB_DEVICE_PERRMISSION:
                    break;
                case USB_DEVICE_DETACHED:
                    break;
            }
        }
    };

    private static final int BURNER_FW_SUCCESS = 0;
    private static final int BURNER_FW_FAILED = 1;

    private Handler mHanderBurnerFW = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {

                case BURNER_FW_SUCCESS:
                    BurnerFwStatusShow(true);
                    //NativeMethods.getInstance().RestartDevice();
                    isBusy = false;
                    startBurnFirewareBtn.setEnabled(true);
                    break;
                case BURNER_FW_FAILED:
                    BurnerFwStatusShow(false);
                    isBusy = false;
                    startBurnFirewareBtn.setEnabled(true);
                    break;
            }
        }
    };

    public void onProgress(float progress) {
        try {
            curProgress.setProgress((int)(progress * 10000));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    void BurnerFwStatusShow(boolean successed)
    {
        if(successed) {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("SonixCamera")
                    .setMessage("Brun Fireware Successed")
                    .setPositiveButton("OK", null)
                    .show();
        }else{
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("SonixCamera")
                    .setMessage("Brun Fireware Fail!")
                    .setPositiveButton("OK", null)
                    .show();
        }
    }

    private void UpdateCameraInfo() {

        ArrayList<CameraControlTransfer> devList = UstorageDeviceInstance.getInstance().devListArray;
        for (CameraControlTransfer devInfo : devList) {
            if (!devInfo.bPermission) {
                return;
            }
            Log.d("UpdateCameraInfo->dev", devInfo.dev.toString());
            boolean bClaim = devInfo.connection.claimInterface(devInfo.dev.getInterface(0), true);
            //devInfo.connection.releaseInterface(devInfo.dev.getInterface(0));
            Log.d("UpdateCameraInfo->bClaim", String.valueOf(bClaim));
            NativeMethods.getInstance().UnInitialize();
            Log.d("UpdateCameraInfo", "Start init");
            boolean r = NativeMethods.getInstance().Initialize(devInfo);
            if (r) {
                Toast ts = Toast.makeText(getBaseContext(),"设备插入",Toast.LENGTH_LONG);
                ts.show();

                cct = devInfo;

                devNameTextView.setText("    Device Name: ");
                byte data[] = new byte[100];
                java.util.Arrays.fill(data, (byte) 0);
                if (NativeMethods.getInstance().GetProduct(data, 100)) {
                    if (data[0] != 0xFF) {
                        String devName = new String(data);
                        devNameTextView.setText("    Device Name: " + devName);
                    }
                }

                fwVersionTextView.setText("Fireware Name: ");
                java.util.Arrays.fill(data, (byte) 0);
                //if (NativeMethods.getInstance().GetSerialNumber(data, 100)){
                //if (NativeMethods.getInstance().GetManufacturer(data, 100)){
                //if (NativeMethods.getInstance().GetInterface(data, 100)){
                //if (NativeMethods.getInstance().GetString3(data, 100)){
                if (NativeMethods.getInstance().GetFwVersion(data, 100, true)) {
                    if (data[0] != 0xFF) {
                        String fwVersion = new String(data);
                        fwVersionTextView.setText("Fireware Name: " + fwVersion);
                    }
                }




//                int addr = 0x8600;
//                byte val[] = new byte[1];
//                r = NativeMethods.getInstance().AsicRegisterRead(addr, val, 1);
//                val[0] &= 0xfd;
//                r = NativeMethods.getInstance().AsicRegisterWrite(addr, val, 1);
//                addr = 0x8201;
//                r = NativeMethods.getInstance().AsicRegisterRead(addr, val, 1);
//                val[0] |= 0x04;
//                r = NativeMethods.getInstance().AsicRegisterWrite(addr, val, 1);
//                byte testVal[] = new byte[2];
//                java.util.Arrays.fill(testVal, (byte) 0);
//                byte slaveId = 0x6c;
//                byte addrByteNum = 1;
//                byte dataByteNum = 2;
//                r = NativeMethods.getInstance().SensorTwoRegisterCustomRead(slaveId, 0x53, addrByteNum, testVal, dataByteNum, false);

//
//                byte src[] = new byte[] {0, 1};
//                byte src1[] = new byte[] {2, 3};
//                byte src2[] = new byte[] {4, 5};
//                byte src3[] = new byte[] {6, 7};
//                r = NativeMethods.getInstance().SensorRegisterCustomWrite(slaveId, 0x55, addrByteNum, src, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomWrite(slaveId, 0x55, addrByteNum, src1, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomWrite(slaveId, 0x55, addrByteNum, src2, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomWrite(slaveId, 0x55, addrByteNum, src3, dataByteNum, false);
//
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                byte hardwareDec[] = new byte[] {0, 0};
//                byte hardwareDec1[] = new byte[] {0, 0};
//                byte hardwareDec2[] = new byte[] {0, 0};
//                byte hardwareDec3[] = new byte[] {0, 0};
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec1, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec2, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec3, dataByteNum, false);
//
//                try {
//                    Thread.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                byte hardwareDec4[] = new byte[] {0, 0};
//                byte hardwareDec5[] = new byte[] {0, 0};
//                byte hardwareDec6[] = new byte[] {0, 0};
//                byte hardwareDec7[] = new byte[] {0, 0};
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec4, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec5, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec6, dataByteNum, false);
//                r = NativeMethods.getInstance().SensorRegisterCustomRead(slaveId, 0x5A, addrByteNum, hardwareDec7, dataByteNum, false);


//                    //Serial Flash Read/Write Test
//                    final NativeMethods.SERIAL_FLASH_TYPE sft = NativeMethods.SERIAL_FLASH_TYPE.SFT_UNKNOW;
//                    if(!NativeMethods.getInstance().GetSerialFlashType(sft, true)){
//                        Log.i("test", "GetSerialFlashType failed");
//                        return;
//                    }
//                    byte val[] = new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ,17 ,18 ,19, 20, 21};
//                    r = NativeMethods.getInstance().SerialFlashSectorWrite(sft, 0x1f000, val, 15);
//                    java.util.Arrays.fill(data, (byte) 0);
//                    r =  NativeMethods.getInstance().SerialFlashRead(0x1f000, data, 15);

                break;
            }
        }

    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        readAiscRegisterBtn =(Button)findViewById(R.id.id_reg_read_btn);
        writeAiscRegisterBtn =(Button)findViewById(R.id.id_reg_write_btn);
        startBurnFirewareBtn =(Button)findViewById(R.id.id_btn_start_burn_fw);
        asicRegisterAddrTextEdit =(EditText)findViewById(R.id.id_reg_addr_text_edit);
        asicRegisterDataTextEdit =(EditText)findViewById(R.id.id_reg_data_text_edit);
        curProgress =(ProgressBar)findViewById(R.id.id_progressbar_cur_progress);
        curProgress.setMax(10000);


        devNameTextView = (TextView)findViewById(R.id.id_textview_dev_name);
        fwVersionTextView  = (TextView)findViewById(R.id.id_textview_fw_version);

        fwFileNameListView =(ListView)findViewById(R.id.id_fireware_file_list_view);
        class FirewareListViewAdapter extends BaseAdapter {
            private Context context;
            private ArrayList<String> mFileList;
            HashMap<String,Boolean> radioBtnStatus=new HashMap<String,Boolean>();

            public FirewareListViewAdapter(Context context, ArrayList<String> files) {
                this.context = context;
                this.mFileList = files;
            }

            @Override
            public int getCount() {
                if (mFileList != null && mFileList.size() > 0) {
                    return mFileList.size();
                }
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                View item = View.inflate(MainActivity.this, R.layout.fireware_file_list_view_item, null);
                item.setBackgroundColor(0xFFFFFF);
                TextView name = (TextView) item.findViewById(R.id.id_textview_fireware_file_name);
                item.setBackgroundColor(0xFFFFFFFF);
                name.setText(mFileList.get(position));

                final RadioButton radioBtn = (RadioButton) item.findViewById(R.id.id_radiobutton_fireware_file_name);
                radioBtn.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        for (String key : radioBtnStatus.keySet()) {
                            radioBtnStatus.put(key, false);
                        }
                        radioBtnStatus.put(String.valueOf(position), radioBtn.isChecked());
                        FirewareListViewAdapter.this.notifyDataSetChanged();
                    }
                });
                boolean res = false;
                if (radioBtnStatus.get(String.valueOf(position)) == null || radioBtnStatus.get(String.valueOf(position)) == false) {
                    res = false;
                    radioBtnStatus.put(String.valueOf(position), false);
                } else {
                    res = true;
                }
                radioBtn.setChecked(res);
                if (res) {
                    selFileNameIndex = position;
                    Log.d("selFileNameIndex", String.valueOf(position));
                } else {
                    radioBtn.setChecked(false);
                }
                return item;
            }

            @Override
            public Object getItem(int position) {
                return mFileList.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }
        }

        int checkCode = ActivityCompat.checkSelfPermission(MainActivity.this, "android.permission.READ_EXTERNAL_STORAGE");
        if(checkCode != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA, "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"},1);
        }

        checkStorageManagerPermission();

        fwFileNames = new ArrayList<String>();
        fwFilePaths = new ArrayList<String>();
        selFileNameIndex = -1;

        StorageManager mStorageManager;
        mStorageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        //获取所有挂载的设备（内部sd卡、外部sd卡、挂载的U盘）
        List<StorageVolume> volumes = mStorageManager.getStorageVolumes();
        try {
            Class<?> storageVolumeClazz = Class
                    .forName("android.os.storage.StorageVolume");
            //通过反射调用系统hide的方法
            Method getPath = storageVolumeClazz.getMethod("getPath");
            Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
            for (int i = 0; i < volumes.size(); i++) {
                StorageVolume storageVolume = volumes.get(i);//获取每个挂载的StorageVolume

                //通过反射调用getPath、isRemovable
                String storagePath = (String) getPath.invoke(storageVolume); //获取路径
                boolean isRemovableResult = (boolean) isRemovable.invoke(storageVolume);//是否可移除
                String description = storageVolume.getDescription(this);

                File fileDir = new File(storagePath);
                File[] files = fileDir.listFiles();
                for(File file : files){
                    if(!file.isDirectory()){
                        if(file.exists()){
                            String path = file.getPath();
                            String extName = path.substring(path.lastIndexOf(".") + 1);
                            if(extName.equals("src")  || extName.equals("bin")){
                                String abPath = file.getAbsolutePath();
                                String caPath = file.getCanonicalPath();
                                file.setReadable(true);
                                boolean canRead = file.canRead();
                                FileInputStream fis = new FileInputStream(file.getPath());
                                fis.available();
                                byte[]buffer = new byte[4];
                                int len = 0;
                                if(fis.read(buffer, 0, 4) != -1){
                                    int a = buffer[0];
                                    if(buffer[0] == 83 && buffer[1] == 78 && buffer[2] == 57 &&  buffer[3] == 67){
                                        fwFileNames.add(file.getName());
                                        fwFilePaths.add(path);
                                    }
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            Log.d("jason", " e:" + e);

//            File dir = null;
//            dir = Environment.getExternalStorageDirectory();
//            String rootPath = dir.toString();
//            boolean sdCardExist = false;
//            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//                sdCardExist=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
//            }
//            if(sdCardExist) {
//                dir = Environment.getExternalStorageDirectory();//获取跟目录
//            }

            String rootPath = null;
            for (int i = 0; i < volumes.size(); i++) {
                rootPath = volumes.get(i).getDirectory().toString();

                try {
                    File fileDir = new File(rootPath);
                    File[] files = fileDir.listFiles();
                    for (File file : files) {
                        if (!file.isDirectory()) {
                            if (file.exists()) {
                                String path = file.getPath();
                                String extName = path.substring(path.lastIndexOf(".") + 1);
                                if (extName.equals("src") || extName.equals("bin")) {
                                    String abPath = file.getAbsolutePath();
                                    String caPath = file.getCanonicalPath();
                                    file.setReadable(true);
                                    boolean canRead = file.canRead();
                                    FileInputStream fis = new FileInputStream(file.getPath());
                                    fis.available();
                                    byte[] buffer = new byte[4];
                                    int len = 0;
                                    if (fis.read(buffer, 0, 4) != -1) {
                                        int a = buffer[0];
                                        if (buffer[0] == 83 && buffer[1] == 78 && buffer[2] == 57 && buffer[3] == 67) {
                                            fwFileNames.add(file.getName());
                                            fwFilePaths.add(path);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e1) {
                }
            }
        }


        if (fwFileNames != null && fwFileNames.size() > 0) {
            Log.d("fwFileNames Num", String.valueOf(fwFileNames.size()));
            FirewareListViewAdapter adapter = new FirewareListViewAdapter(this, fwFileNames);
            fwFileNameListView.setAdapter(adapter);
            fwFileNameListView.setVisibility(View.VISIBLE);
        }

        startBurnFirewareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(cct == null){
                    Toast ts = Toast.makeText(getBaseContext(),"No camera device found!",Toast.LENGTH_SHORT);
                    ts.show();
                    return;
                }

                if(selFileNameIndex < 0){
                    Log.i("test", "mFwPathName is null");
                    Toast ts = Toast.makeText(getBaseContext(),"mFwPathName is null!",Toast.LENGTH_SHORT);
                    ts.show();
                    return;
                }

                final NativeMethods.SERIAL_FLASH_TYPE sft = NativeMethods.SERIAL_FLASH_TYPE.SFT_UNKNOW;
                if(!NativeMethods.getInstance().GetSerialFlashType(sft, true)){
                    Log.i("test", "GetSerialFlashType failed");
                    return;
                }
                Log.i("test", "sft= " + sft.getValue());

                if(sft.getValue() == 0){
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("SonixCamera")
                            .setMessage("get flash type failed!")
                            .setPositiveButton("OK", null)
                            .show();
                    //return;
                    Log.i("test", "set sft= " + NativeMethods.SERIAL_FLASH_TYPE.SFT_MXIC.toString());
                    sft.setValue(NativeMethods.SERIAL_FLASH_TYPE.SFT_MXIC.ordinal());
                }

                String path = fwFilePaths.get(selFileNameIndex);

                NativeMethods.ASIC_ROM_TYPE romType = NativeMethods.ASIC_ROM_TYPE.ART_Unknow;
                int chipID[] = new int[1];
                if(!NativeMethods.getInstance().GetAsicRomType(romType, chipID)){
                    Log.i("ERROR", "get chip rom type failed!");
                    return;
                }
                Log.d("RomType", String.valueOf(chipID[0]));
                try{
                    FileInputStream fis = new FileInputStream(path);
                    fis.available();
                    byte[]buffer = new byte[7];
                    int len = 0;
                    if(fis.read(buffer, 0, 7) != -1) {
                        if(buffer[5] < 48 || buffer[5] >=65 || buffer[6] < 48 || buffer[6] >=65 ){
                            Log.e("ERROR", "The selected firmware and device do not match!");
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("SonixCamera")
                                    .setMessage("Not a standard firmware file!")
                                    .setPositiveButton("OK", null)
                                    .show();
                            return;
                        }
                        int id = (buffer[5] - 48) * 16 + (buffer[6] - 48);
                        if(id != chipID[0]){
                            Log.e("ERROR", "The selected firmware and device do not match!");
                            new AlertDialog.Builder(MainActivity.this)
                                    .setTitle("SonixCamera")
                                    .setMessage("The selected firmware and device do not match!")
                                    .setPositiveButton("OK", null)
                                    .show();
                            return;
                        }

                    }
                }catch (Exception e) {
                    Log.e("ERROR", "Read fw file failed!");
                }

                startBurnFirewareBtn.setEnabled(false);
                new Thread(new Runnable() {
                    @Override
                    public void run() {

//                        NativeMethods me = new NativeMethods();
//                        NativeMethods.ChangeParamInfo paramInfo = NativeMethods.getInstance().new ChangeParamInfo();
//                        paramInfo.SerialNumberLength = 6;
//                        paramInfo.strSerialNumber = "SN0001";
//                        paramInfo.ProductLength = 6;
//                        paramInfo.strProduct = "SN0002";
//                        paramInfo.ManufactureLength = 6;
//                        paramInfo.strManufacture = "SN0003";
//                        paramInfo.VidPidLength = 8;
//                        paramInfo.strVidPid = "0c356363";
//                        paramInfo.String3Length = 6;
//                        paramInfo.strString3 = "SN0004";
//                        paramInfo.InterfaceLength = 6;
//                        paramInfo.strInterface = "SN0005";
                        //if(!NativeMethods.getInstance().CustomBurnerFW(paramInfo, MainActivity.this, path, sft, true)){
                        //if(!NativeMethods.getInstance().SetParamTableFromFWFile(paramInfo, MainActivity.this, path, sft, true)){

                        if(!NativeMethods.getInstance().BurnerFW(MainActivity.this, path, sft, true)){
                            mHanderBurnerFW.sendEmptyMessage(BURNER_FW_FAILED);

                            return;
                        }
                        mHanderBurnerFW.sendEmptyMessage(BURNER_FW_SUCCESS);
                    }
                }).start();
                isBusy = true;
            }
        });

        readAiscRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isBusy){
                    return;
                }
                if(cct == null){
                    Toast ts = Toast.makeText(getBaseContext(),"No camera device found!",Toast.LENGTH_SHORT);
                    ts.show();
                    return;
                }

                if(asicRegisterAddrTextEdit.getText().toString().isEmpty()){
                    return;
                }
                int addr = Integer.valueOf(asicRegisterAddrTextEdit.getText().toString(), 16);
                byte data[] = new byte[2];
                if(!NativeMethods.getInstance().AsicRegisterRead(addr, data, 1)){
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("SonixCamera")
                            .setMessage("AsicRegisterRead fail!")
                            .setPositiveButton("OK", null)
                            .show();
                    return;
                }

                asicRegisterDataTextEdit.setText(String.format("%x", data[0]));
            }
        });

        writeAiscRegisterBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isBusy){
                    return;
                }

                if(cct == null){
                    Toast ts = Toast.makeText(getBaseContext(),"No camera device found!",Toast.LENGTH_SHORT);
                    ts.show();
                    return;
                }

                if(asicRegisterAddrTextEdit.getText().toString().isEmpty() || asicRegisterDataTextEdit.getText().toString().isEmpty()){
                    return;
                }
                int addr = Integer.valueOf(asicRegisterAddrTextEdit.getText().toString(), 16);
                byte data[] = new byte[1];
                data[0] = (byte)Integer.valueOf(asicRegisterDataTextEdit.getText().toString(), 16).intValue();
                if(!NativeMethods.getInstance().AsicRegisterWrite(addr, data, 1)){
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("SonixCamera")
                            .setMessage("AsicRegisterWrite fail!")
                            .setPositiveButton("OK", null)
                            .show();
                    return;
                }
            }
        });

        UstorageDeviceInstance.getInstance().tryAttcheDeviceHandle(MainActivity.this, MainActivity.this);

    }

    public static String getStoragePath(Context mContext,String keyword) {
        String targetpath = "";
        StorageManager mStorageManager = (StorageManager) mContext
                .getSystemService(Context.STORAGE_SERVICE);
        Class<?> storageVolumeClazz = null;
        try {
            storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");

            Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");

            Method getPath = storageVolumeClazz.getMethod("getPath");

            Object result = getVolumeList.invoke(mStorageManager);

            final int length = Array.getLength(result);

            Method getUserLabel = storageVolumeClazz.getMethod("getUserLabel");


            for (int i = 0; i < length; i++) {

                Object storageVolumeElement = Array.get(result, i);

                String userLabel = (String) getUserLabel.invoke(storageVolumeElement);

                String path = (String) getPath.invoke(storageVolumeElement);

                if(userLabel.contains(keyword)){
                    targetpath = path;
                }

            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return targetpath ;
    }

    private void checkStorageManagerPermission() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R ||  Environment.isExternalStorageManager()) {
            Toast.makeText(this, "已获得访问所有文件权限", Toast.LENGTH_SHORT).show();
        } else {
            new AlertDialog.Builder(MainActivity.this)
                    .setTitle("SonixCamera")
                    .setMessage("本程序需要您同意允许访问所有文件权限!")
                    .setPositiveButton("OK", null)
                    .show();

            Intent intent = new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 1);
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1 :
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    Log.d("SonixCameraDemo", "获取到权限: ");
                }
        }
    }

    @Override
    public void usbDeviceInsert() {
        mHander.sendEmptyMessage(USB_DEVICE_INSERT);
    }

    @Override

    public void permissionFinish(boolean isSuccessful, CUSBListener.UsbControlBlock ctrlBlock) {
        synchronized (this) {
        }
    }

    @Override
    public void usbDeviceDetached() {
    }

}